package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Company;
import model.User;
import service.CompanyService;
import service.impl.CompanyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Author: 燕子豪
 * @Date: 2022/12/18 11:11
 */
@WebServlet("/companyLogin")
public class CompanyLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符格式
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        CompanyService companyService = new CompanyServiceImpl();

        //解析前端并转为json类型
        BufferedReader reader = new BufferedReader(request.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //接收数据
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        //获取session
        HttpSession session = request.getSession();
        Company company = companyService.login(username, password);

        JSONObject message = new JSONObject();
        //判断用户名或者密码是否错误
        if (company == null) {
            //状态0表示出错，1代表正确
            message.put("status", "0");
            message.put("Msg", "公司名或者密码错误");
            response.getWriter().write(message.toString());
            return;
        }
        //将user加入到会话中
        session.setAttribute("company", company);
        //向前端发送正确的状态已经要跳转的页面
        message.put("status", "1");
        //暂时空着，对接时再补充
        message.put("companyMsg", company);
        response.getWriter().write(message.toString());
    }
}
